module FreMeter (
  input rstn,
  input clk_std,
  input clk_test,
  input gate,
  output reg [31:0] data_fre
);


localparam fre_std = 32'd200_000_000;


// 门限同步被测信号
reg cnt_en;

always @(posedge clk_test, negedge rstn) begin
  if(!rstn) begin
    cnt_en <= 1'b0;
  end
  else begin
    cnt_en <= gate;
  end
end


// 标准时钟计数
reg [31:0] cnt_std;

always @(posedge clk_std, negedge rstn) begin
  if(!rstn) begin
    cnt_std <= 32'd0;
  end
  else if(cnt_en) begin
    cnt_std <= cnt_std + 32'd1;
  end
  else begin
    cnt_std <= 32'd0;
  end
end


// 被测时钟计数
reg [31:0] cnt_test;

always @(posedge clk_test, negedge rstn) begin
  if(!rstn) begin
    cnt_test <= 32'd0;
  end
  else if(cnt_en) begin
    cnt_test <= cnt_test + 32'd1;
  end
  else begin
    cnt_test <= 32'd0;
  end
end


// 获取计数结果
reg [31:0] result_std;
reg [31:0] result_test;

always @(negedge cnt_en, negedge rstn) begin
  if(!rstn) begin
    result_std <= 32'd0;
    result_test <= 32'd0;
  end
  else begin
    result_std <= cnt_std;
    result_test <= cnt_test;
  end 
end


// 计算结果f_test = f_std * result_test / result_std
reg [63:0] tmp_mult;

always @(posedge clk_std, negedge rstn) begin
  if(!rstn) begin
    tmp_mult <= 64'd0;
  end
  else if(cnt_en == 1'd0) begin
    tmp_mult <= fre_std * result_test;
  end
  else begin
    tmp_mult <= 64'd0;
  end
end

always @(posedge clk_std, negedge rstn) begin
  if(!rstn) begin
    data_fre <= 32'd0;
  end
  else if(cnt_en == 1'd0) begin
    data_fre <= tmp_mult / result_std;
  end
  else begin
   data_fre <= 32'd0;
  end
end


endmodule